package net.pws.oos.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import net.pws.common.util.DateUtils;
import net.pws.common.util.StringUtils;
import net.pws.common.jackson.JsonUtils;
import net.pws.common.persistence.EntityManager;
import net.pws.common.simplemq.DataQueueProcessor;
import net.pws.oos.biz.model.Attachment;
import net.pws.oos.biz.model.Checkin;
import net.pws.oos.biz.model.User;
import net.pws.oos.biz.query.AttachmentFinder;
import net.pws.oos.biz.query.CheckinFinder;
import net.pws.oos.biz.query.parameter.CheckinQueryParameter;
import net.pws.oos.biz.service.export.CheckinExcelExportData;
import net.pws.oos.security.SecurityUtils;
import net.pws.oos.web.dto.AttachmentDto;
import net.pws.oos.web.dto.CheckinDto;
import net.pws.oos.web.dto.CheckinEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;

@Controller
@RequestMapping("/biz/checkin")
@SuppressWarnings("rawtypes")
public class CheckinAction implements ServletContextAware{
	
	private final transient Log logger = LogFactory.getLog(CheckinAction.class);
	
	private static final String EXCEL_DOWNLOAD = "/temp";
	
	private static final String SIMPLE_TIME_FORMAT = "yyyyMMddHHmmssSSS";

	@Autowired
	private CheckinFinder checkinFinder;

	@Autowired
	private AttachmentFinder attachmentFinder;

	@Autowired
	private EntityManager entityManager;
	
	@Autowired
    @Qualifier("checkinExcelExportProcessor")
	private DataQueueProcessor checkinExcelExportProcessor;
	
	@Autowired
    @Qualifier("attachmentPath")
    private String attachmentPath;
	
	private ServletContext context;
    
    public void setServletContext(ServletContext context) {
        this.context = context;
    }

	@RequestMapping("/calendar.do")
	public String calendarPage(String userId, ModelMap map) {
		User user = null;
		if (StringUtils.isNotBlank(userId)) {
			user = entityManager.find(User.class, userId);
		}
		if (user == null) {
			user = SecurityUtils.currentUser();
		}

		map.put("userId", user.getId());
		map.put("userName", user.getName());

		return "checkin/calendar";
	}

	@RequestMapping("/list.json")
	@ResponseBody
	public Object listCheckin(String userId, long from, long to) {
		Map<String, Object> data = new HashMap<String, Object>();
		if (StringUtils.isBlank(userId)) {
			userId = SecurityUtils.currentUserId();
		}
		try {
			Date start = new Date(from);
			Date end = new Date(to);
			List<Checkin> list = checkinFinder.list(userId, start, end);
			List<CheckinEvent> events = CheckinEvent.from(list);

			data.put("success", 1);
			data.put("result", events);
		} catch (Exception e) {
			data.put("success", 0);
			data.put("error", e.getMessage());
		}
		return data;
	}

	@RequestMapping("/detail.do")
	public String detailPage(String id, ModelMap map) {
		map.put("id", id);
		return "checkin/detail";
	}

	@RequestMapping("/detail.json")
	@ResponseBody
	public Object getCheckin(String id) {
		if (StringUtils.isEmpty(id)) {
			return JsonUtils.failedMap("错误的参数！");
		}

		Checkin model = checkinFinder.get(id);
		if (model == null) {
			return JsonUtils.failedMap("您查找的考勤信息不存在！");
		}

		return JsonUtils.succeedMap(CheckinDto.from(model));
	}

	@RequestMapping("/attachment/list.json")
	@ResponseBody
	public Object getAttachmentList(String resourceId) {
		if (StringUtils.isBlank(resourceId)) {
			return JsonUtils.failedMap("未指定考勤！");
		}

		List<Attachment> list = attachmentFinder.getPhotos(resourceId);
		List<AttachmentDto> dtos = new ArrayList<AttachmentDto>();
		for (Attachment att : list) {
			dtos.add(AttachmentDto.from(att));
		}
		return JsonUtils.succeedMap(dtos);
	}
	
	/**
     * 任务查询页面
     * 
     * @return
     */
    @RequestMapping("/query.do")
    public String queryPage(CheckinQueryParameter parameter, ModelMap map) {
        Date today = new Date();
        Date firstDay = DateUtils.addMonth(today, -3);//3个月前
//        		getFirstDay();
        
        String startDate = null;
        if (parameter.getStartDate() == null) {
            startDate = DateUtils.getDateStr(firstDay);
        }
        else {
            startDate = DateUtils.getDateStr(parameter.getStartDate());
        }
        
        String endDate = null;
        if (parameter.getEndDate() == null) {
            endDate = DateUtils.getDateStr(today);
        }
        else {
            endDate = DateUtils.getDateStr(parameter.getEndDate());
        }
        
//        String projectId = "";
//        String projectName = "";
//        if (StringUtils.isNotBlank(parameter.getProjectId())) {
//            Project project = entityManager.find(Project.class,
//                                                 parameter.getProjectId());
//            if (project != null) {
//                projectId = project.getId();
//                projectName = project.getName();
//            }
//        }
        
        map.put("startDate", startDate);
        map.put("endDate", endDate);
//        map.put("projectId", projectId);
//        map.put("projectName", projectName);
        return "checkin/query";
    }
    
    @RequestMapping("/count.json")
    @ResponseBody
    public Object getTaskCount(CheckinQueryParameter param) {
        param = initParametersByRole(param);
        return countTasks(param);
    }
    
    private Object countTasks(CheckinQueryParameter param) {
        try {
            return JsonUtils.succeedMap(checkinFinder.countCheckin(param));
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/queryList.json")
    @ResponseBody
    public Object getTaskList(CheckinQueryParameter param) {
        param = initParametersByRole(param);
        
        return listCheckins(param);
    }
    
    private CheckinQueryParameter initParametersByRole(CheckinQueryParameter param) {
        if (param == null) {
            param = new CheckinQueryParameter();
        }
        
        if (StringUtils.areBlank(param.getExecPersonId(), param.getExecOrganId())) {
            if (SecurityUtils.isManager()) {
                param.setExecOrganId(SecurityUtils.currentUser().getOrganId());
            }
            else {
                param.setExecPersonId(SecurityUtils.currentUserId());
            }
        }
        return param;
    }
    
    private Object listCheckins(CheckinQueryParameter param) {
        try {
        	List<Map> checkins = checkinFinder.getCheckinList(param, param.getStart(), param.getLimit());
            return JsonUtils.succeedMap(checkins);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }

    @RequestMapping("/excel.json")
    @ResponseBody
    public Object exportExcel(CheckinQueryParameter parameter) {
        try {
            parameter = initParametersByRole(parameter);
            CheckinExcelExportData data = new CheckinExcelExportData();
            data.setQueryParameter(parameter);
            data.setAttachmentRoot(getAttachmentRoot());
            
            User user = SecurityUtils.currentUser();
            StringBuilder excelUri = new StringBuilder(EXCEL_DOWNLOAD);
            excelUri.append("/")
                    .append("CheckinExport_")
                    .append(user.getAccount())
                    .append("_")
                    .append(DateUtils.getDateStr(data.getCreateTime(),
                                                 SIMPLE_TIME_FORMAT))
                    .append(".xlsx");
            data.setExcelUri(excelUri.toString());
            data.setExcelPath(context.getRealPath(data.getExcelUri()));
            data.setUserId(user.getId());
            checkinExcelExportProcessor.getDataPipe().addLazyData(data, 1);
            return JsonUtils.succeedMap(null);
        }
        catch (Exception e) {
            logger.error("AddCheckinExcelExport error", e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    /**
     * 得到文件系统中附件根目录的绝对路径
     * 
     * @return
     */
    private String getAttachmentRoot() {
        if (StringUtils.isBlank(attachmentPath)) {
            attachmentPath = context.getRealPath(Attachment.ATTACHMENT_ROOT);
        }
        return attachmentPath;
    }
}
